<template>
  <div class="container">
    <Breadcrumb :items="['menu.list', '部门管理']" />
    <a-card class="general-card" title="部门管理">
      <div class="right-btn">
        <el-button plan type="primary" @click="actionFn('add', {}, {})"
          >新增根节点</el-button
        >
      </div>
      <el-tree
        :data="treeData"
        :props="treeProps"
        node-key="id"
        :expand-on-click-node="false"
        :default-expand-all="false"
        v-loading="listLoading"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span class="tree-node-row">
              <span class="tree-node-label">{{ node.label }}</span>
              <span class="node-actions">
                <el-button
                  link
                  type="primary"
                  @click="actionFn('add', node, data)"
                >
                  新增部门
                </el-button>
                <el-button
                  link
                  type="primary"
                  @click="actionFn('edit', node, data)"
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click="actionFn('del', node, data)"
                >
                  删除
                </el-button>
              </span>
            </span>
          </span>
        </template>
      </el-tree>

      <!-- 新增部门弹框 -->
      <el-dialog
        v-model="showAddModal"
        :title="titleType[dialogType]"
        width="600px"
      >
        <!-- 使用 Tabs 切换详情和日志 -->
        <formCom
          ref="formComDom"
          :option="option"
          :key-count="state.keyCount"
          @submit-fn="submitFn"
          @cancle-fn="closeDialog"
        />

        <!-- <template #footer>
          <span class="dialog-footer">
            <el-button @click="onCancel">取 消</el-button>
            <el-button type="primary" @click="onConfirm">确 定</el-button>
          </span>
        </template> -->
      </el-dialog>
    </a-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import { useRouter, useRoute } from 'vue-router';
  import { ElMessageBox, ElMessage } from 'element-plus';
  import { useList } from '@/use/index';
  import {
    deptTreeApi,
    deptAddApi,
    deptUpdateApi,
    deptDelApi,
  } from '@/utils/apiConfig';
  import useUserStore from '@/store/modules/user';
  import { setDeptListVuex } from '@/utils/util';
  const router = useRouter();
  const route = useRoute();
  const {} = route.query;
  const state = reactive({ keyCount: 1 });
  const userStore = useUserStore();
  const treeProps = {
    children: 'children',
    label: 'deptName',
  };
  const listLoading = ref(false);
  const dialogType = ref('add');
  const dialogItem: any = ref({});
  const titleType: any = {
    add: '新增部门',
    edit: '编辑部门',
    detail: '部门详情',
  };
  // Tab 状态：默认显示详情
  const activeDetailTab = ref('detail');
  // 日志数据

  const option = reactive({
    labelWidth: '100px',
    isBetween: false,
    showSubmit: true,
    position: 'left',
    formList: [
      {
        label: '部门名称',
        val: '',
        field: 'departmentName',
        type: 'input',
        width: '100%',
        require: true,
        maxlength: 50,
      },
    ],
  });

  const showAddModal = ref(false);

  const treeData: any = ref([]);
  async function inits() {
    listLoading.value = true;
    const res = await setDeptListVuex();
    console.log('deptList', res);
    treeData.value = res || [];
    listLoading.value = false;
  }

  function closeDialog() {
    showAddModal.value = false;
    option.formList.forEach((item) => {
      item.val = '';
    });
    state.keyCount += 1;
  }
  function submitFn(obj: any) {
    console.log(111111, obj);
    // list.value.push(obj);

    switch (dialogType.value) {
      case 'add':
        deptAddApi({ ...obj, parentDeptNumber: dialogItem.value?.deptNo })
          .then((res) => {
            console.log('add-res', res);
            inits();
            ElMessage({
              message: '新增部门成功',
              type: 'success',
            });
          })
          .catch((err) => {
            console.log('add-err', err);
          });
        break;

      case 'edit':
        const deptNo: any = dialogItem.value?.deptNo;

        deptUpdateApi({
          departmentName: obj.departmentName,
          deptNo,
          //   parentDeptNumber: '',
          //   deptNameEn: '',
        })
          .then((res) => {
            console.log('update-res', res);
            inits();
            ElMessage({
              message: '更新部门成功',
              type: 'success',
            });
          })
          .catch((err) => {
            console.log('update-err', err);
          });
        break;
      case 'detail':
        break;
      default:
        break;
    }

    closeDialog();
  }

  // 弹框与表单

  const addFormRef = ref<FormInstance>();
  const newItem = ref({
    departmentName: '',
    departmentType: '',
    desc: '',
    tag: '',
  });
  function actionFn(type: string, node: any, item: any) {
    console.log(type, item);
    dialogType.value = type;
    dialogItem.value = item;
    switch (type) {
      case 'detail':
        activeDetailTab.value = 'detail';
        option.showSubmit = false;
        option.formList.forEach((one) => {
          one.val = item[one.field];
          one.disabled = true;
        });
        state.keyCount += 1;
        showAddModal.value = true;
        break;
      case 'add':
        // activeDetailTab.value = 'detail';
        showAddModal.value = true;
        break;
      case 'del':
        console.log(item.departmentName);
        ElMessageBox.confirm('确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            console.log('del-api');
            const deptNo = item?.deptNo;
            deptDelApi({ addPath: deptNo })
              .then((res) => {
                console.log('del-res', res);
                inits();
                ElMessage({
                  message: '删除部门成功',
                  type: 'success',
                });
              })
              .catch((err) => {
                console.log('del-err', err);
              });
          })
          .catch(() => {});
        break;

      case 'edit':
        activeDetailTab.value = 'detail';

        option.showSubmit = true;

        option.formList[0].val = item.deptName; // 这里接口字段不一致
        state.keyCount += 1;
        showAddModal.value = true;
        break;
      case 'refresh':
        alert('刷新传感器');
        break;
      default:
        break;
    }
  }
  onMounted(() => {
    inits();
  });
</script>

<style lang="less" scoped>
  .container {
    padding: 20px;
  }
</style>

<style scoped>
  .tree-node-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%; /* 占满当前行，提高 hover 命中范围 */
    padding: 4px 8px; /* 可选：增加可点击/悬停区域 */
  }

  .node-actions {
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.15s ease;
    min-width: calc(100vw - 500px);
    padding-left: 30px;
  }

  :deep(.el-tree-node__content :hover .node-actions) {
    opacity: 1;
    pointer-events: auto;
  }
</style>
